//
//  ScanQRCodeVC.m
//  LiteraryTune
//
//  Created by xingyi on 2018/11/30.
//  Copyright © 2018 cxd. All rights reserved.
//

#import "ScanQRCodeVC.h"
#import <AVFoundation/AVFoundation.h>
#import <QuickLook/QuickLook.h>

@interface ScanQRCodeVC ()<AVCaptureMetadataOutputObjectsDelegate,QLPreviewControllerDelegate,QLPreviewControllerDataSource>

/** 捕捉会话 */
@property (nonatomic, weak) AVCaptureSession *session;
/** 预览图层 */
@property (nonatomic, weak) AVCaptureVideoPreviewLayer *layer;

@property (strong, nonatomic)QLPreviewController *previewController;

@property (strong, nonatomic) NSURL *fileUrl;

@end

@implementation ScanQRCodeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor blackColor];
    self.previewController  =  [[QLPreviewController alloc]  init];
    self.previewController.dataSource  = self;
    
    // 1. 创建捕捉会话
    AVCaptureSession *session = [[AVCaptureSession alloc] init];
    self.session = session;
    
    // 2. 添加输入设备(数据从摄像头输入)
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    [session addInput:input];
    
    // 3. 添加输出数据接口
    AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
    output.rectOfInterest = CGRectMake((self.view.bounds.size.width - 200) / 2 / self.view.bounds.size.width, (self.view.bounds.size.height - 200) / 2 / self.view.bounds.size.height, 200, 200);
    // 设置输出接口代理
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    [session addOutput:output];
    // 3.1 设置输入元数据的类型(类型是二维码数据)
    // 注意，这里必须设置在addOutput后面，否则会报错
    [output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];
    
    // 4.添加扫描图层
    AVCaptureVideoPreviewLayer *layer = [AVCaptureVideoPreviewLayer layerWithSession:session];
    layer.frame = self.view.bounds;
    [self.view.layer addSublayer:layer];
    self.layer = layer;
    
    CALayer *boardLayer = [[CALayer alloc] init];
    boardLayer.borderWidth = 0.5;
    boardLayer.borderColor = [UIColor greenColor].CGColor;
    boardLayer.frame = CGRectMake((kScreenWidth - 200) / 2, (kScreenHeight - 200) / 2, 200, 200);
    [self.view.layer addSublayer:boardLayer];
    
    UILabel *label = [[UILabel alloc] init];
    label.frame = CGRectMake(0, boardLayer.frame.origin.y - 30, kScreenWidth, 20);
    label.font = [UIFont systemFontOfSize:12];
    label.textColor = [UIColor greenColor];
    label.textAlignment = NSTextAlignmentCenter;
    label.text = @"扫码阅读图书";
    [self.view addSubview:label];
    
    CAShapeLayer *shapelayer = [[CAShapeLayer alloc] init];;
    CGRect allRect = self.view.bounds;
    CGRect centerRect = boardLayer.frame;
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, nil, allRect);
    CGPathAddRect(path, nil, centerRect);
    [shapelayer setFillRule:kCAFillRuleEvenOdd];
    shapelayer.path = path;
    shapelayer.fillColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.7].CGColor;
    [self.layer addSublayer:shapelayer];
    
    // 5. 开始扫描
    [session startRunning];
    
    UIButton *closeBtn = [[UIButton alloc] init];
    closeBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [closeBtn setTitle:@"关闭" forState:UIControlStateNormal];
    [closeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [closeBtn addTarget:self action:@selector(closeBtnDidClick:) forControlEvents:UIControlEventTouchUpInside];
    closeBtn.frame = CGRectMake(kScreenWidth - 55, UIApplication.sharedApplication.statusBarFrame.size.height, 44, 44);
    [self.view addSubview:closeBtn];
}

- (void)closeBtnDidClick:(UIButton *)sender {
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - <AVCaptureMetadataOutputObjectsDelegate>

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    if (metadataObjects.count) {// 扫描到了数据
        AVMetadataMachineReadableCodeObject *object = [metadataObjects lastObject];
        
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        
        AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
        NSURL *URL = [NSURL URLWithString:object.stringValue];
        NSURLRequest *request = [NSURLRequest requestWithURL:URL];
        [SVProgressHUD showWithStatus:@""];
        NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress *downloadProgress){
            
        } destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
            NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
            NSURL *url = [documentsDirectoryURL URLByAppendingPathComponent:[NSURL URLWithString:object.stringValue].lastPathComponent];
            return url;
        } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
            [SVProgressHUD dismiss];
            self.fileUrl = filePath;
            [self dismissViewControllerAnimated:NO completion:nil];
            UITabBarController *tab = (UITabBarController *)UIApplication.sharedApplication.keyWindow.rootViewController;
            UINavigationController *nav = tab.selectedViewController;
            [nav.topViewController presentViewController:self.previewController animated:YES completion:nil];
            //刷新界面,如果不刷新的话，不重新走一遍代理方法，返回的url还是上一次的url
            [self.previewController refreshCurrentPreviewItem];
        }];
        [downloadTask resume];
        
        // 停止扫描
        [self.session stopRunning];
        
        // 将预览图层移除
//        [self.layer removeFromSuperlayer];
    }else{
        NSLog(@"没有扫描到数据");
    }
}

-(NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller
{
    return 1; //需要显示的文件的个数
}
-(id<QLPreviewItem>)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index
{
    //返回要打开文件的地址，包括网络或者本地的地址
    NSURL * url = self.fileUrl;
    return url;
}

@end
